import os
import subprocess
import threading

from django.apps import AppConfig
from django.core.management import call_command

from mqtest.management.commands import filewatch


class MqtestConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'mqtest'

    def ready(self):
        # if os.environ.get('RUN_MAIN') == 'true':
        #     if not is_port_in_use(8001):
        #         subprocess.Popen("uvicorn djangoProject.asgi:application --host 127.0.0.1 --port 8001", shell=True)
        if os.environ.get('RUN_MAIN') == 'true':  # 只在主进程启动时才执行

            def run_filewatch():
                call_command('filewatch')

            t = threading.Thread(target=run_filewatch, daemon=True)
            t.start()


import socket


def is_port_in_use(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('127.0.0.1', port)) == 0
